import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _initializerDefineProperty from "@babel/runtime/helpers/esm/initializerDefineProperty";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _initializerWarningHelper from "@babel/runtime/helpers/esm/initializerWarningHelper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _omit from "lodash/omit";
import _isNil from "lodash/isNil";
import _isFunction from "lodash/isFunction";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _class, _class2, _descriptor;

/* eslint-disable no-unused-expressions */

/* eslint-disable func-names */
import React from 'react';
import { Button, Form, Input, Row, Spin, Table, InputNumber, DatePicker, Select, Col } from 'antd';
import moment from 'moment';
import qs from 'querystring';
import { Bind } from 'lodash-decorators';
import { createPagination, getCurrentOrganizationId, getResponse, getDateFormat, getDateTimeFormat } from "../../../../utils/utils";
import intl from "../../../../utils/intl";
import { DEFAULT_DATETIME_FORMAT, DEFAULT_DATE_FORMAT } from "../../../../utils/constants";
import { totalRender } from "../../../../utils/renderer";
import notification from "../../../../utils/notification";
import request from "../../../../utils/request";
import { getEnvConfig } from "../../../../utils/iocUtils";
import { queryLovData } from "../../../../services/api";
import styles from "./index.less?modules";
var FormItem = Form.Item;
var formItemLayout = {
  labelCol: {
    sm: {
      span: 8
    }
  },
  wrapperCol: {
    sm: {
      span: 14
    }
  }
};

var _getEnvConfig = getEnvConfig('config'),
    CPAAS_PLATFORM = _getEnvConfig.CPAAS_PLATFORM;

var defaultRowKey = 'lovId';
var pageSizeOptions = ['10', '20', '50', '100'];
var LovMultiModal = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(LovMultiModal, _React$Component);

  var _super = _createSuper(LovMultiModal);

  function LovMultiModal(props) {
    var _this2;

    _classCallCheck(this, LovMultiModal);

    _this2 = _super.call(this, props);

    _initializerDefineProperty(_this2, "setChildren", _descriptor, _assertThisInitialized(_this2));

    _this2.state = {
      selectedKeys: [],
      filterRows: [],
      filtered: false,
      selectedPagination: {
        pageSizeOptions: pageSizeOptions,
        pageSize: 10,
        showSizeChanger: true,
        showTotal: function showTotal(total, range) {
          return totalRender(total, range);
        }
      },
      loading: false,
      selectAllLoading: false,
      translateLoading: false,
      tempSize: 0,
      currentRecords: []
    };
    _this2.firstLoadFinshed = false;
    return _this2;
  }

  _createClass(LovMultiModal, [{
    key: "setSateData",
    value: function setSateData(state) {
      if (this.mounted) {
        this.setState(state);
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var currentValue = this.props.currentValue;
      var selectedPagination = this.state.selectedPagination;
      var values = _isNil(currentValue) || currentValue === '' ? [] : String(currentValue).split(',');

      if (values.length > 0) {
        this.setState({
          selectedKeys: values,
          selectedPagination: _objectSpread(_objectSpread({}, selectedPagination), {}, {
            total: values.length
          })
        });
        this.translate(values.slice(0, 10), this.setCurrentRecords);
      }

      this.mounted = true;
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var lov = this.props.lov;

      if (!this.firstLoadFinshed && !_isEmpty(lov)) {
        var _lov$tableFields = lov.tableFields,
            tableFields = _lov$tableFields === void 0 ? [] : _lov$tableFields;

        if (tableFields.length > 0) {
          var scrollX = tableFields.reduce(function (p, n) {
            return p + n.width || 0;
          }, 0);
          tableFields[tableFields.length - 1].width = undefined; // eslint-disable-next-line react/no-did-update-set-state

          scrollX > 600 && this.setState({
            scrollX: scrollX
          });
        }

        this.firstLoadFinshed = true;
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.mounted = false;
    }
  }, {
    key: "processQueryParams",
    value: function processQueryParams(pagination) {
      var filter = this.props.form.getFieldsValue();
      var _this$props$lov = this.props.lov,
          queryUrl = _this$props$lov.queryUrl,
          pageSize = _this$props$lov.pageSize,
          lovCode = _this$props$lov.lovCode,
          lovTypeCode = _this$props$lov.lovTypeCode,
          _this$props$lov$query = _this$props$lov.queryFields,
          queryFields = _this$props$lov$query === void 0 ? [] : _this$props$lov$query;
      var _this$props$queryPara = this.props.queryParams,
          queryParams = _this$props$queryPara === void 0 ? {} : _this$props$queryPara;
      var nowQueryParams = queryParams || {};

      if (_isFunction(nowQueryParams)) {
        nowQueryParams = nowQueryParams();
      }

      var queryIndex = queryUrl.indexOf('?');
      var sourceQueryParams = {};

      if (queryIndex !== -1) {
        sourceQueryParams = qs.parse(queryUrl.substr(queryIndex + 1));
      }

      var formatFilter = _objectSpread({}, filter);

      queryFields.forEach(function (item) {
        if (item.dataType === 'DATE' || item.dataType === 'DATETIME') {
          if (filter[item.field]) {
            formatFilter[item.field] = moment(filter[item.field]).format(item.dataType === 'DATETIME' ? DEFAULT_DATETIME_FORMAT : DEFAULT_DATE_FORMAT);
          }
        }
      });

      var sourceParams = _objectSpread(_objectSpread(_objectSpread({}, formatFilter), {}, {
        page: pagination.current - 1 || 0,
        size: pagination.pageSize || pageSize
      }, sourceQueryParams), nowQueryParams);

      var params = lovTypeCode !== 'URL' ? Object.assign(sourceParams, {
        lovCode: lovCode
      }) : sourceParams;
      var url = getUrl(queryUrl, queryParams, queryIndex);
      return {
        params: params,
        url: url
      };
    }
  }, {
    key: "formReset",
    value: function formReset() {
      this.props.form.resetFields();
    }
    /**
     * 树 child 属性更改
     * @param {Array} list 原树结构数据
     * @param {String} childName 要替换的 childName
     */

  }, {
    key: "dataFilter",
    value:
    /**
     * 处理返回列表数据
     * @param {Object|Array} data - 返回的列表数据
     */
    function dataFilter(data) {
      var _this$props$lov2 = this.props.lov,
          _this$props$lov2$valu = _this$props$lov2.valueField,
          rowkey = _this$props$lov2$valu === void 0 ? defaultRowKey : _this$props$lov2$valu,
          childrenFieldName = _this$props$lov2.childrenFieldName;

      var isTree = _isArray(data);

      var hasParams = !_isEmpty(Object.values(this.props.form.getFieldsValue()).filter(function (e) {
        return e !== undefined && e !== '';
      }));
      var list = isTree ? this.setChildren(data, childrenFieldName) : data.content;
      var pagination = !isTree && createPagination(data);
      var treeKeys = []; // 树状 key 列表

      if (isTree && hasParams) {
        /**
         * 遍历生成树列表
         * @param {*} treeList - 树列表数据
         */
        var flatKeys = function flatKeys(treeList) {
          if (_isArray(treeList.children) && !_isEmpty(treeList.children)) {
            treeKeys.push(treeList[rowkey]);
            treeList.children.forEach(function (item) {
              return flatKeys(item);
            });
          } else {
            treeKeys.push(treeList[rowkey]);
          }
        };

        list.forEach(function (item) {
          return flatKeys(item);
        }); // 遍历生成 key 列表
      }

      this.setSateData({
        list: list,
        treeKeys: treeKeys,
        pagination: pagination
      });
    }
  }, {
    key: "defineProperty",
    value: function defineProperty(obj, property, value) {
      Object.defineProperty(obj, property, {
        value: value,
        writable: true,
        enumerable: false,
        configurable: true
      });
    }
    /**
     * 访问对象由字符串指定的多层属性
     * @param {Object} obj 访问的对象
     * @param {String} str 属性字符串，如 'a.b.c.d'
     */

  }, {
    key: "parseField",
    value: function parseField(obj, str) {
      if (/[.]/g.test(str)) {
        var arr = str.split('.');
        var newObj = obj[arr[0]];
        var newStr = arr.slice(1).join('.');
        return this.parseField(newObj, newStr);
      }

      return String(obj[str]);
    }
  }, {
    key: "splitGroupSelect",
    value: function splitGroupSelect(_ref) {
      var resolve = _ref.resolve,
          onError = _ref.onError,
          onFinish = _ref.onFinish;

      var _this$processQueryPar = this.processQueryParams({
        current: 1,
        pageSize: 500
      }, 'right'),
          params = _this$processQueryPar.params,
          url = _this$processQueryPar.url;

      var _this = this;

      function select(queryParams) {
        var _this3 = this;

        queryLovData(url, queryParams).then(function (res) {
          if (getResponse(res)) {
            var data = processTreeData(res.content || []); // eslint-disable-next-line no-unused-expressions

            resolve && resolve(data);

            if (res.number < res.totalPages) {
              select(_objectSpread(_objectSpread({}, queryParams), {}, {
                page: res.number + 1
              }));
            } else {
              _this.setState({
                selectAllLoading: false
              }, onFinish);
            }
          }
        }).catch(function () {
          notification.error(); // eslint-disable-next-line no-unused-expressions

          onError && onError();

          _this3.setState({
            selectAllLoading: false
          });
        });
      }

      this.setState({
        selectAllLoading: true
      });
      select(params);
    }
  }, {
    key: "onReset",
    value: function onReset() {
      this.formReset();
      this.setState({
        filterRows: [],
        filtered: false
      });
    }
  }, {
    key: "onSearchSelected",
    value: function onSearchSelected() {
      var _this4 = this;

      var _this$props$lov$value = this.props.lov.valueField,
          valueField = _this$props$lov$value === void 0 ? defaultRowKey : _this$props$lov$value;
      this.setState({
        filterRows: [],
        filtered: true
      });
      this.splitGroupSelect({
        resolve: function resolve(data) {
          var _this4$state = _this4.state,
              filterRows = _this4$state.filterRows,
              selectedKeys = _this4$state.selectedKeys;
          var newRows = data.filter(function (item) {
            return selectedKeys.includes(_this4.parseField(item, valueField));
          });

          _this4.setState({
            filterRows: [].concat(_toConsumableArray(filterRows), _toConsumableArray(newRows))
          });
        }
      });
    }
  }, {
    key: "onPagination",
    value: function onPagination() {
      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var current = pagination.current,
          pageSize = pagination.pageSize;
      var _this$state = this.state,
          selectedKeys = _this$state.selectedKeys,
          filterRows = _this$state.filterRows;

      if (filterRows.length === 0) {
        var start = (current - 1) * pageSize;
        var end = start + pageSize;
        this.translate(selectedKeys.slice(start, end), this.setCurrentRecords);
        this.setState({
          selectedPagination: pagination
        });
      } else {
        this.setState({
          selectedPagination: pagination
        });
      }
    }
  }, {
    key: "translate",
    value: function () {
      var _translate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(values, onSuccess) {
        var _this5 = this;

        var code;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                code = this.props.code;
                this.setState({
                  translateLoading: true
                });
                return _context.abrupt("return", request("".concat(CPAAS_PLATFORM, "/v1/").concat(getCurrentOrganizationId(), "/ui-customize/translateLov?lovViewCode=").concat(code), {
                  body: values,
                  method: 'POST'
                }).then(function (res) {
                  if (getResponse(res)) {
                    var resArr = values.map(function (i) {
                      return _omit(res[i], 'children');
                    });
                    onSuccess && onSuccess(resArr);
                    return resArr;
                  }
                }).finally(function () {
                  _this5.setState({
                    translateLoading: false
                  });
                }));

              case 3:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function translate(_x, _x2) {
        return _translate.apply(this, arguments);
      }

      return translate;
    }()
  }, {
    key: "setCurrentRecords",
    value: function setCurrentRecords(res) {
      this.setState({
        currentRecords: res
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this6 = this;

      var _this$props = this.props,
          lov = _this$props.lov,
          form = _this$props.form,
          width = _this$props.width,
          _this$props$ldpData = _this$props.ldpData,
          ldpData = _this$props$ldpData === void 0 ? {} : _this$props$ldpData,
          lovLoadLoading = _this$props.lovLoadLoading,
          _this$props$queryInpu = _this$props.queryInputProps,
          queryInputProps = _this$props$queryInpu === void 0 ? {} : _this$props$queryInpu,
          _this$props$isDbc2Sbc = _this$props.isDbc2Sbc,
          isDbc2Sbc = _this$props$isDbc2Sbc === void 0 ? true : _this$props$isDbc2Sbc;

      if (lovLoadLoading) {
        return /*#__PURE__*/React.createElement(Spin, {
          spinning: true
        });
      }

      var _this$state2 = this.state,
          loading = _this$state2.loading,
          selectedPagination = _this$state2.selectedPagination,
          selectedKeys = _this$state2.selectedKeys,
          currentRecords = _this$state2.currentRecords,
          filterRows = _this$state2.filterRows,
          selectAllLoading = _this$state2.selectAllLoading,
          translateLoading = _this$state2.translateLoading,
          scrollX = _this$state2.scrollX,
          tempSize = _this$state2.tempSize,
          filtered = _this$state2.filtered;
      var disableTranslate = filterRows.length > 0 || filtered;
      var _lov$tableFields2 = lov.tableFields,
          tableFields = _lov$tableFields2 === void 0 ? [] : _lov$tableFields2,
          _lov$queryFields = lov.queryFields,
          queryFields = _lov$queryFields === void 0 ? [] : _lov$queryFields,
          _lov$valueField = lov.valueField,
          rowkey = _lov$valueField === void 0 ? defaultRowKey : _lov$valueField;
      var getFieldDecorator = form.getFieldDecorator;

      var rightPagination = _objectSpread(_objectSpread({}, selectedPagination), {}, {
        pageSize: tempSize + selectedPagination.pageSize
      });

      if (!disableTranslate) {
        rightPagination.total = selectedKeys.length;
      }

      var rightScroll = {
        x: scrollX,
        y: rightPagination.pageSize > 10 ? 365 : undefined
      };
      var selectedTableProps = {
        rowKey: function rowKey(record) {
          return _this6.parseField(record, rowkey);
        },
        loading: selectAllLoading || translateLoading,
        columns: tableFields,
        dataSource: disableTranslate ? filterRows : currentRecords,
        scroll: rightScroll,
        bordered: true,
        pagination: rightPagination,
        onChange: this.onPagination
      }; // 查询条件表单

      var span = queryFields.length <= 1 || width <= 400 ? 24 : 12;
      var queryInput = queryFields.map(function () {
        var queryItem = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        var valueListData = ldpData[queryItem.sourceCode] || [];

        switch (queryItem.dataType) {
          case 'INT':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(InputNumber, {
              style: {
                width: '100%'
              },
              onPressEnter: _this6.queryData
            }))));

          case 'DATE':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(DatePicker, {
              style: {
                width: '100%'
              },
              placeholder: "",
              format: getDateFormat()
            }))));

          case 'DATETIME':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(DatePicker, {
              style: {
                width: '100%'
              },
              placeholder: "",
              showTime: {
                format: DEFAULT_DATETIME_FORMAT
              },
              format: getDateTimeFormat()
            }))));

          case 'SELECT':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(Select, {
              allowClear: true,
              style: {
                width: '100%'
              }
            }, valueListData.map(function (item) {
              return /*#__PURE__*/React.createElement(Select.Option, {
                value: item.value,
                key: item.value
              }, item.meaning);
            })))));

          default:
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(Input, Object.assign({
              dbc2sbc: isDbc2Sbc
            }, queryInputProps)))));
        }
      });
      return /*#__PURE__*/React.createElement("div", {
        className: styles['lovmulti-wrapper']
      }, queryFields.length > 0 ? /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          marginBottom: '10px',
          alignItems: 'flex-start'
        }
      }, /*#__PURE__*/React.createElement(Row, {
        style: {
          flex: 'auto'
        },
        className: "query-fields"
      }, queryInput), /*#__PURE__*/React.createElement("div", {
        className: "lov-modal-btn-container"
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.onReset,
        style: {
          marginRight: 8
        }
      }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        htmlType: "submit",
        onClick: this.onSearchSelected,
        loading: loading,
        style: {
          marginRight: 8
        }
      }, intl.get('cpaas.common.button.search').d('查询')))) : null, /*#__PURE__*/React.createElement(Table, selectedTableProps));
    }
  }]);

  return LovMultiModal;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "processQueryParams", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "processQueryParams"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "formReset", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "formReset"), _class2.prototype), _descriptor = _applyDecoratedDescriptor(_class2.prototype, "setChildren", [_dec4], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function initializer() {
    var _this7 = this;

    return function (data, childName) {
      return childName ? data.map(function (n) {
        var item = n;

        if (!_isEmpty(n[childName])) {
          _this7.defineProperty(item, 'children', [_objectSpread({}, n[childName])]);
        }

        if (!_isEmpty(item.children)) {
          item.children = _this7.setChildren(item.children);
        }

        return item;
      }) : data;
    };
  }
}), _applyDecoratedDescriptor(_class2.prototype, "dataFilter", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "dataFilter"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "defineProperty", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "defineProperty"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "parseField", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "parseField"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "splitGroupSelect", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "splitGroupSelect"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onReset", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "onReset"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onSearchSelected", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "onSearchSelected"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onPagination", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "onPagination"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "translate", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "translate"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "setCurrentRecords", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "setCurrentRecords"), _class2.prototype)), _class2)) || _class);
export { LovMultiModal as default };
/**
 * 替换查询 Url 中的变量
 * @param {String} url
 * @param {Object} data
 */

function getUrl(url, data, queryIndex) {
  var ret = url;
  var organizationRe = /\{organizationId\}|\{tenantId\}/g;
  Object.keys(data).map(function (key) {
    var re = new RegExp("{".concat(key, "}"), 'g');
    ret = ret.replace(re, data[key]);
    return ret;
  });

  if (organizationRe.test(ret)) {
    ret = ret.replace(organizationRe, getCurrentOrganizationId());
  }

  var index = ret.indexOf('?'); // 查找是否有查询条件

  if (queryIndex !== -1) {
    ret = ret.substr(0, index);
  }

  return ret;
}

function processTreeData(data) {
  var res = [];
  data.forEach(function (item) {
    res.push(_omit(item, ['children']));

    if (item.children) {
      res = res.concat(processTreeData(item.children));
    }
  });
  return res;
}